package server;

import server.dao.SessionMap;
import server.pojo.*;
import server.utils.Util;

import java.util.List;
import java.util.Map;

public class Handler {

	private Teacher t;

	public Teacher getT() {
		return t;
	}

	public Handler(Teacher teacher) {
		t = teacher;
	}

	public static void register(Map<String, String> map) {
		for (var str : map.values()) {
			if (str.contains("'"))
				throw new RuntimeException("invalid character.");
		}
		try (var s = Util.getSqlSession()) {
			var list = s.getMapper(SessionMap.class)
					.select(Long.parseLong(map.get("id")), null);
			if (!list.isEmpty())
				throw new RuntimeException("ID has already been registered");
			s.getMapper(SessionMap.class)
					.insert(map);
		}
	}

	public static Teacher login(long id, String pswd) {
		if (pswd.contains("'"))
			throw new RuntimeException("invalid character");
		try (var s = Util.getSqlSession()) {
			var list = s.getMapper(SessionMap.class)
					.select(id, pswd);
			if (list.isEmpty())
				throw new RuntimeException("ID dont match any of password or no register");
			return list.get(0);
		}
	}

	public void update(Map<String, String> map) {
		for (var str : map.values()) {
			if (str.contains("'"))
				throw new RuntimeException("invalid character.");
		}
		map.put("id", Long.toString(t.id)); //override
		try (var s = Util.getSqlSession()) {
			s.getMapper(SessionMap.class)
					.update(map);
			t.id = Long.parseLong(map.getOrDefault("id", String.valueOf(t.id)));
			t.name = map.getOrDefault("name", t.name);
			t.sex = map.getOrDefault("sex", t.sex);
			t.grade = Integer.parseInt(map.getOrDefault("grade", String.valueOf(t.grade)));
			t.pswd = map.getOrDefault("pswd", t.pswd);
			t.t = Integer.parseInt(map.getOrDefault("t", String.valueOf(t.t)));
			t.depart_id = Long.parseLong(map.getOrDefault("depart_id", String.valueOf(t.depart_id)));
		}
	}

	public void delete() {
		try (var s = Util.getSqlSession()) {
			s.getMapper(SessionMap.class)
					.delete(t.id);
		}
	}

	public List<Apply> selectItem() {
		try (var s = Util.getSqlSession()) {
			if (t.t == 1)
				return s.getMapper(SessionMap.class)
						.selectItem(t.id);
			else
				return s.getMapper(SessionMap.class)
						.selectItem2(t.depart_id);
		}
	}

	public void updateItem(PassState state, String apply_id) {
		if (apply_id.contains("'"))
			throw new RuntimeException("invalid character.");
		try (var s = Util.getSqlSession()) {
			s.getMapper(SessionMap.class)
					.updateItem(state, apply_id);
		}
	}

	public List<Notice> selectNotice() {
		try (var s = Util.getSqlSession()) {
			return s.getMapper(SessionMap.class)
					.selectNotice();
		}
	}

	public void insertNotice(Notice x) {
		if ((x.id + x.title + x.text + x.teacher_name).contains("'"))
			throw new RuntimeException("invalid character.");
		try (var s = Util.getSqlSession()) {
			s.getMapper(SessionMap.class)
					.insertNotice(x);
		}
	}
}
